import React from "react";
import { useNavigate } from "react-router-dom";
import useSWR from "swr";
import { fetcher } from "../utils";
import "./course.css";

function ClassList(props) {
    const navigate = useNavigate();
    const { data: classList, error } = useSWR("/api/class/list", fetcher);
    const { data: courseList } = useSWR("/api/course/list", fetcher);
    const safeClassList = Array.isArray(classList) ? classList : [];
    const safeCourseList = Array.isArray(courseList) ? courseList : [];

    const getCourseName = (sn) => {
        const c = safeCourseList.find(c => c.sn === sn);
        return c ? c.name : sn;
    };

    return (
        <div className="paper">
            <div className="paper-head">
                <h3>班级信息列表</h3>
                <button className="btn" onClick={() => navigate("/class/new")}>
                    新建班次
                </button>
            </div>
            <div className="paper-body">
                <table className="table">
                    <thead>
                        <tr>
                            <th>班次名称</th>
                            <th>所属课程</th>
                            <th>上课时间/地点</th>
                        </tr>
                    </thead>
                    <tbody>
                        {error && <tr><td colSpan="3">加载失败</td></tr>}
                        {!classList && !error && <tr><td colSpan="3">加载中...</td></tr>}
                        {Array.isArray(classList) && classList.length === 0 && <tr><td colSpan="3">暂无班次</td></tr>}
                        {safeClassList.map(cls => (
                            <tr key={cls.sn}>
                                <td>{cls.name}</td>
                                <td>{getCourseName(cls.course_sn)}</td>
                                <td>{cls.schedule}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

export default ClassList;